package com.xuwang.interceptor;

import com.xuwang.Util.JWTutil;
import com.xuwang.pojo.User;
import com.xuwang.service.impl.PublicInfoServiceImpl;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @ Author  460503919
 * @ Date    2021/8/18 14:22
 * @ VERSION 1.0.0
 */
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 服务对象
     */
    @Resource
    private PublicInfoServiceImpl publicInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String oldToken= request.getHeader("Authorization");
        if (oldToken!=null) {
            String userName = JWTutil.getUserName(oldToken);
            User user=publicInfoService.checkUserName(userName);
            Map<String, String> map;
            map = new HashMap<>();
            map.put("username", user.getUsername());
            map.put("identity", user.getIdentity() + "");
            String token = JWTutil.createToken(map);
            response.setHeader("Access-control-Expose-Headers", "authorization");
            response.setHeader("authorization", token);
            return true;
        } else
            response.sendRedirect("/html/login.html");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("返回视图前我执行了");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("整个流程执行之后我执行");
    }
}
